package com.yzw.phonestoreservice.controller;

import com.yzw.phonecommen.common.R;
import com.yzw.phonestoreservice.annotation.UnInterception;
import com.yzw.phonestoreservice.exception.PhoneException;
import com.yzw.phonestoreservice.form.AddressForm;
import com.yzw.phonestoreservice.pojo.BuyerAddress;
import com.yzw.phonestoreservice.service.BuyerAddressService;
import com.yzw.phonestoreservice.vo.BuyerAddressVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.xml.crypto.Data;
import java.util.List;

/**
 * @BelongsProject: phonestoresys
 * @BelongsPackage: com.yzw.phonestoreservice.controller
 * @Author: yanhongwei
 * @CreateTime: 2022-11-07  19:21
 * @Description: TODO
 * @Version: 1.0
 */
@RequestMapping("buyer/address")
@RestController
@Slf4j
public class BuyerAddressController {

    @Autowired
    private BuyerAddressService buyerAddressService;

    @GetMapping("/list")
    @UnInterception
    public R buyerAddressList(){
       List<BuyerAddressVo> buyerAddressList = buyerAddressService.addressList();
        return R.ok().data("data",buyerAddressList);
    }

    @PostMapping("/create")
    @UnInterception
    public R buyerAddressCreate(@Valid @RequestBody AddressForm buyerAddress, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("添加地址数据校验错误");
            //bindingResult.getFieldError().getDefaultMessage()   得到校验直接上的 message 属性
            throw new PhoneException(bindingResult.getFieldError().getDefaultMessage());
        }
        Boolean b = buyerAddressService.buyerAddressCreate(buyerAddress);
        return b?R.ok():R.error();
    }
    @PutMapping("/update")
    @UnInterception
    public R buyerAddressUpdate(@Valid @RequestBody AddressForm buyerAddress, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("添加地址数据校验错误");
            //bindingResult.getFieldError().getDefaultMessage()   得到校验直接上的 message 属性
            throw new PhoneException(bindingResult.getFieldError().getDefaultMessage());
        }
        Boolean b = buyerAddressService.buyerAddressCreate(buyerAddress);
        return b?R.ok():R.error();
    }
    @PutMapping("/del")
    @UnInterception
    public R buyerAddressDel(@RequestBody BuyerAddress buyerAddress){
        Boolean b = buyerAddressService.buyerAddressDel(buyerAddress.getAddressId());
        return b?R.ok():R.error();
    }

}
